<?php

/**
 * Created by PhpStorm.
 * User: Jie
 * Date: 4/13/2016
 * Time: 3:41 PM
 */
class OrderController extends \Core_BaseCtl {
    
    
    //获取优惠券卡劵
    protected  function getCard($openid){
        Yaf_Loader::import(APP_PATH . 'library/Weixin/wechatCard.php');
        $weixincard = new wechatCard();
        $card = $weixincard->getUseableCard($openid);
        if(empty($card)){
            return false;
        }
        return $card;
    }

    //套餐内下单
    public function makeComboOrderAction() {
        $comboModel = new ComboModel();
        $combo = $comboModel->getLists(array("where" => array("status" => 1),'order'=>'sort '));
//        echo '<pre>';
//        print_r($combo);exit;
        foreach ($combo as $k => $v) {
            $combo[$k]['content'] = htmlspecialchars_decode($v['content']);
        }
       // print_r($combo);exit;
        $deposit = Tools_help::getDeposit();
        $mini_deposit = Tools_help::getMini_deposit();
        
        $card = $this->getCard($this->openid);
       // print_R($card);exit;
        $this->_view->assign('combo', $combo);
        $this->_view->assign('card', $card);
        $this->_view->assign('deposit', $deposit);
        $this->_view->assign('mini_deposit', $mini_deposit);
        $this->_view->assign('pageTitle', '在线套餐下单');
    }

    public function addComboOrderAction() {
        if ($this->getRequest()->isPost()) {
            $pdata = $this->getAllPost();
            $pdata['openID'] = $this->openid;

            if (!$pdata['openID']) {
                $content = "openID不存在！";
                $url = "/order/makeComboOrder";
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            }

            //用户不能在一天提交超过10次
            $cache_config = $this->config['cache'];
            $cache_config['cache_dir'] .= '/userip';
            $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
            $userip = Tools_help::getIp();      
            $check = $cache->get(md5($userip));
            $history = array();
            if ($check) {
                if ($check['count'] >= 10) {
                    $content = "提交次数一天不能超过10次";
                    $url = "/order/makeComboOrder";
                    $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
                    exit;
                }
                $history['count'] = $check['count'] + 1;
            } else {
                $history['count'] = 1;
            }
            $check = $cache->set(md5($userip), $history, 3600 * 24);


            //print_r($pdata);exit;
            $orderModel = new OrderModel();
            $result = $orderModel->validation->validate($pdata, 'only_combo');
                        

            if ($result) {
                // 入库前数据处理 
                $insert = array();
                $rend = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 4);  //生成随机数
                $insert['order_place'] = 1;
                $insert['meal_type'] = 1;
                $insert['client_type'] = 'C';
                $insert['order_number'] = 'TC-C-' . $rend;
                $insert['client_name'] = $pdata['client_name'];
                $insert['client_phone'] = $pdata['client_phone'];
                $insert['start_address'] = $pdata['start_address'];
                $insert['arrive_address'] = $pdata['arrive_address'];
                $insert['carrydate'] = strtotime($pdata['carrydate']);
                $insert['is_bill'] = $pdata['is_bill'] ? $pdata['is_bill'] : 0;
                
                //优惠券
                if(!empty($pdata['cardID']) && !empty($pdata['card_code']) ){
                    $insert['cardID'] = $pdata['cardID'];
                    $insert['card_code'] = $pdata['card_code'];
                }

                $comboModel = new ComboModel();
                $combo = $comboModel->select(array('where' => array('id' => $pdata['combo_id'])));
               
                $insert['option_list'] = json_encode(array($combo['name']));
                $insert['content_list'] = json_encode(array($combo['content']));
                $insert['price_list'] = json_encode(array($combo['price']));
                $insert['deposit_rate'] = Tools_help::getDeposit();
                $insert['must_price'] = $combo['price'];
                $insert['total_price'] = $combo['price'];
                $insert['createtime'] = time();
                $insert['openID'] = $pdata['openID'];
                //print_r($insert);exit;
                $result = $orderModel->insert($insert);

                if ($result) {
                    // 提示信息并跳转到列表
                    $order = $orderModel->select(array('field' => array('order_number'), 'where' => array('order_number' => $insert['order_number'])));
                    $this->redirect(Tools_help::url("order/weixinPay?order_number=".$order['order_number']));exit;
                } else {
                    $content = "插入有误1！";
                    $url = "/order/makeComboOrder";
                    $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));exit;
                }
            } else {
                $content = "参数有误1！";
                $url = "/order/makeComboOrder";
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));exit;
            }
        } else {
            $content = "验证操作1！";
            $url = "/order/makeComboOrder";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));exit;
        }
        exit;
    }

    public function getitemsAction() {
        $ic_id = $this->getp('ic_id', 0);
        if (empty($ic_id)) {
            die(json_encode(0));
        }

        $model = new ItemsModel();
        $result = $model->getLists(array('where' => array('ic_id' => $ic_id)));
        if ($result) {
            die(json_encode($result));
        }
        die(json_encode(0));
    }

    //非套餐下单
    public function makeOrderAction() {
        $orderModel = new OrderModel();
        $surchargeModel = new SurchargeModel();
        $itemCategoryModel = new ItemscategoryModel();
        $modelsModel = new ModelsModel();
        $serviceModel = new ServiceModel();

        //业务类型
        $service = $serviceModel->getLists(array('order'=>'sort'));

        //附加费
        $type0 = $surchargeModel->getLists(array('where' => array('type' => 0)));
        $type1 = $surchargeModel->getLists(array('where' => array('type' => 1)));
        $type2 = $surchargeModel->getLists(array('where' => array('type' => 2)));

        //大件物品
        $tiemCate = $itemCategoryModel->getLists();
        //print_r($tiemCate);exit;
        //车型
        $models = $modelsModel->getLists();

        //订金比例
        $deposit = Tools_help::getDeposit();
        $mini_deposit = Tools_help::getMini_deposit();
        
        $card = $this->getCard($this->openid);

        // 模版分配数据
        $this->_view->assign('card', $card);
        $this->_view->assign("deposit", $deposit);
        $this->_view->assign("mini_deposit", $mini_deposit);
        $this->_view->assign("type0", $type0);
        $this->_view->assign("type1", $type1);
        $this->_view->assign("type2", $type2);
        $this->_view->assign("service", $service);
        $this->_view->assign('itemCate', $tiemCate);
        $this->_view->assign("order", $orderModel);
        $this->_view->assign("models", $models);
        $this->_view->assign('pageTitle', '在线下单');
    }

    public function addMakeOrderAction() {

        //验证是否登录
//        $model = new WxuserModel();
//        $model->checkUserIsLogin($id);
//        $this->redirect(Tools_help::url("/index/mobileregister/login"));
        // 实例化Model
        $orderModel = new OrderModel();
        $surchargeModel = new SurchargeModel();
        $itemCategoryModel = new ItemscategoryModel();
        $modelsModel = new ModelsModel();
//        print_r($_POST);exit;
        // 处理post数据
        if ($this->getRequest()->isPost()) {

            // 获取所有post数据
            $pdata = $this->getAllPost();
            $pdata['openID'] = $this->openid;

            if (!$pdata['openID']) {
                $content = "openID不存在！";
                $url = "/order/MakeOrder";
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
            }

            //用户不能在一天提交超过10次
            $cache_config = $this->config['cache'];
            $cache_config['cache_dir'] .= '/userip';
            $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
            $userip = Tools_help::getIp();      
            $check = $cache->get(md5($userip));
            $history = array();
            if ($check) {
                if ($check['count'] >= 10) {
                    $content = "提交次数一天不能超过10次";
                    $url = "/order/makeComboOrder";
                    $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
                    exit;
                }
                $history['count'] = $check['count'] + 1;
            } else {
                $history['count'] = 1;
            }
            $check = $cache->set(md5($userip), $history, 3600 * 24);

            // 验证
            $result = $orderModel->validation->validate($pdata, 'only_addback2');
//            $msg = $orderModel->validation->getErrorSummary();
            // 通过验证
            if ($result) {
                // 入库前数据处理

                $insert = array();
                //优惠券
                if(!empty($pdata['cardID']) && !empty($pdata['card_code']) ){
                    $insert['cardID'] = $pdata['cardID'];
                    $insert['card_code'] = $pdata['card_code'];
                }
                
                $rend = date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 4);  //生成随机数
                $insert['order_place'] = 1;
                $insert['carry_type'] = $pdata['carry_type'];
                $insert['client_type'] = $pdata['client_type'];
                $serviceModel = new ServiceModel();
                $service = $serviceModel->select(array('where'=>array('ser_id'=>$pdata['carry_type'])));
                $insert['order_number'] = $service['ser_code'] . '-' . $pdata['client_type'] . '-' . $rend;
                $insert['client_name'] = $pdata['client_name'];
                $insert['client_phone'] = $pdata['client_phone'];
                $insert['start_address'] = $pdata['start_address'];
                $insert['arrive_address'] = $pdata['arrive_address'];
                $insert['carrydate'] = strtotime($pdata['carrydate']);
                $insert['is_bill'] = $pdata['is_bill'];
                $insert['openID'] = $pdata['openID'];

                $price_list = array();
                $option_list = array();
                $content_list = array();
                
                //大件物品
                if(!empty($pdata['items_id'][0])){
                    //大件物品
                    $itemsModel = new ItemsModel();
                    $items = $itemsModel->search($pdata['items_id']);

                    if ($items) {
                        foreach ($items as $v) {
                            $option_list[] = '大件物品';
                            $content_list[] = $v['item_name'];
                            $price_list[] = $v['price'];
                        }
                    }
                }


                //处理附加
                $surcharge = $surchargeModel->getLists();
                //print_r($surcharge);exit;
                if ($surcharge) {
                    foreach ($surcharge as $v) {
                        $key = array_search($v['scg_id'], $pdata['scg_id']);
                        if ($key !== false) {
                            switch ($v['type']) {
                                case 1 :
                                    $option_list[] = '出发楼层';
                                    $content_list[] = $v['scg_name'];
                                    $price_list[] = $v['scg_price'];
                                    break;
                                case 2 :
                                    $option_list[] = '到达楼层';
                                    $content_list[] = $v['scg_name'];
                                    $price_list[] = $v['scg_price'];
                                    break;
                                case 0 :
                                    $option_list[] = $v['scg_name'];
                                    $content_list[] = $pdata['scg_price'][$key] . $v['unit'] . ' 说明：' . $v['desciption'];
                                    $margin = $pdata['scg_price'][$key] - $v['default_value'];
                                    if ($margin > 0) {
                                        $price = $margin * $v['scg_price'];
                                        $price = number_format($price, 2);
                                    } else {
                                        $price = '0.00';
                                    }
                                    $price_list[] = $price;
                                    break;
                            }
                        }
                    }
                }
//                echo '<pre>';
//               print_r($option_list);
//               print_r($content_list);
//               print_r($price_list);exit;
                //车型
                $models = $modelsModel->select(array('where' => array('m_id' => $pdata['m_id'])));
                if ($models) {
                    $option_list[] = '车辆配置';
                    $content_list[] = $models['m_name'];
                    $price_list[] = $models['m_fee'];
                }

                $insert['option_list'] = json_encode($option_list);
                $insert['content_list'] = json_encode($content_list);
                $insert['price_list'] = json_encode($price_list);
                $insert['deposit_rate'] = Tools_help::getDeposit();
                $insert['total_price'] = array_sum($price_list);
                $insert['must_price'] = $insert['total_price'];
                $insert['createtime'] = time();


                // 入库
                $result = $orderModel->insert($insert);
                if ($result) {

                    // 提示信息并跳转到列表
                    $order = $orderModel->select(array('field' => array('order_number'), 'where' => array('order_number' => $insert['order_number'])));
                    $this->redirect(Tools_help::url("order/weixinPay?order_number=" . $order['order_number']));exit;
                    exit;
                } else {
                    $content = "提交失败！";
                    $url = "/order/makeorder";
                    $this->redirect(Tools_help::url("redirect/error?c='$content&u=$url"));exit;
                }
            } else {
                $content = "验证失败！";
                $url = "/order/makeorder";
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));exit;
            }
        }
       
        exit;
    }

    public function weixinPayAction() {
        $openid = $this->openid;
        //print_r($this->getg('order_number',''));exit;
        //if(!$order_number = $this->getg('order_number','') && !$openid = $this->getg('openid','')){
        if (!$order_number = $this->getg('order_number', '')) {
            $content = "访问有误！";
            $url = "/order/makeorder";
            $this->redirect(Tools_help::url("redirect/error?c='$content&u=$url"));
        }

        $orderModel = new OrderModel();
        $info = $orderModel->select(array('where' => array('order_number' => $order_number)));

        $fee['price_list'] = json_decode($info['price_list']);
        $fee['option_list'] = json_decode($info['option_list']);
        if($info['meal_type'] == 1){
              $fee['content_list'] = json_decode($info['content_list']);
              $fee['content_list'][0] = htmlspecialchars_decode($fee['content_list'][0]);
        }else{
             $fee['content_list'] = json_decode($info['content_list']);
        }
        $fee['total_price'] = $info['total_price'];
        $fee['deposit_rate'] = $info['deposit_rate'];

        $fee['meal_type'] = $info['meal_type'];

        $pay_price = intval(str_replace('.', '', $info['must_price']));
        $deposit = ceil($info['must_price'] * ($info['deposit_rate'] / 100));
        $mini_depoist = Tools_help::getMini_deposit();
        if($deposit < $mini_depoist){
            $deposit = $mini_depoist;
        }

        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Config.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Exception.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Data.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Notify.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Api.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.JsApiPay.php');

        $tools = new JsApiPay();
        $data = new WxPayUnifiedOrder();
        
        //优惠券
        if(!empty($info['cardID']) &&!empty($info['card_code'])){
            
            $cardinfo = $this->getCard($info['openID']);
            
            if($cardinfo == false){
                $content = "优惠券已经过期,请重新下单！";
                $url = "/Mobileregister/userinfo";
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));exit;
            }
            
            $mycard  = array();           
            foreach($cardinfo as $v){
                if($v['cardID'] == $info['cardID'] && $v['card_code'] == $info['card_code']){
                    $mycard['cardID'] = $v['cardID'];
                    $mycard['card_code'] = $v['card_code'];
                    $mycard['card_fee'] = $v['card_fee'];
                    $mycard['card_title'] = $v['card_title'];
                    $deposit -= $v['card_fee'];
                }
            }

            if(empty($mycard)){
                $content = "优惠券已经过期,请重新下单！";
                $url = "/Mobileregister/userinfo";
                $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));exit;
            }
            $coupon_fee = number_format(($mycard['card_fee']/100),2);
            $this->_view->assign('coupon_fee',$coupon_fee);
            $data->SetAttach(json_encode($mycard));
        }

        $data->SetOut_trade_no($order_number);
        $data->SetBody("支付");
        $data->SetTotal_fee(1);  //测试
        //$data->SetTotal_fee($deposit.'00');
        $data->SetTrade_type("JSAPI");
        $data->SetOpenid($info['openID']);
        
        
        $data->SetNotify_url("http://www.dafabanjia888.com/mobileregister/fetchdata");
        $result = WxPayApi::unifiedOrder($data, 32);
        $jsApiParameters = $tools->GetJsApiParameters($result);
        $editAddress = $tools->GetEditAddressParameters();

        $this->_view->assign('jsApiParameters', $jsApiParameters);
        $this->_view->assign('order_number', $order_number);
        $this->_view->assign('openid', $openid);
        $this->_view->assign('editAddress', $editAddress);
        $this->_view->assign('fee', $fee);
        $this->_view->assign('deposit', number_format($deposit,2));

        $this->_view->assign('mini_depoist',$mini_depoist);
        $this->_view->assign("pageTitle", '微信支付');
    }
    
    private  function weixinApiRefund($order_number,$cash_fee){
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Config.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Exception.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Data.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Notify.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.Api.php');
        Yaf_Loader::import(APP_PATH . 'library/Weixin/WxPay.JsApiPay.php');
        $input = new WxPayRefund();
        $input->SetOut_trade_no($order_number);
        
        $input->SetTotal_fee((int)($cash_fee*100));
        $input->SetRefund_fee((int)($cash_fee*100));
        $input->SetOp_user_id(WxPayConfig::MCHID);
        $input->SetOut_refund_no(WxPayConfig::MCHID.date('YmdHis'));
        $result = WxPayApi::refund($input);
        if($result['return_msg'] == 'ok' && $result['return_code']=="SUCCESS"){
            return true;
        }
        return false;

    }

    //退款
    public function refundAction() {
//        $openid = $this->openid;
        $openid = $this->openid;
        $order_number = $this->getg('order_number', '');
        if (empty($openid) || empty($order_number)) {
            $content = "访问有误！";
            $url = "/Mobileregister/orderinfo/order_number/$order_number/openid/$openid";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }

        $orderModel = new OrderModel();
        $info = $orderModel->select(array('where' => array('openid' => $openid, 'order_number' => $order_number)));

        if ($info['order_state'] != 1 || $info['order_state'] == -2 && $info['already_price'] == "0.00" || empty($info['already_price_time'])) {
            die("err");
            $content = "非法操作！";
            $url = "/Mobileregister/userinfo";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }

        $cash_fee = $info['already_price'];
        if (!$this->weixinApiRefund($order_number,$cash_fee)) {
            $content = "退款失败！";
            $url = "/Mobileregister/userinfo";
            $this->redirect(Tools_help::url("redirect/error?c=$content&u=$url"));
        }             
             
        $orderModel->update(array('order_number' => $order_number, 'openid' => $openid), array('order_state' => -2));
        $content = "退款成功！";
        $url = "/Mobileregister/orderinfo/order_number/$order_number/openid/$openid";
        $this->redirect(Tools_help::url("redirect/index?c=$content&u=$url"));
        exit;
    }

    //发送模版消息
    /**
     * 
     * @param type $type //1：支付，2：派车
     */
    private function sendTemp($type, $data, $openid) {
//        $openid ="o3QGWvyynxtKw2PAsy5bxlssICPA";
//        $data['order_number'] = 'fdsfsafa';
//        $data['cash_fee'] = 0.01;
//        $data['time_end'] = time();
        //unset($_SESSION['access_token']);
        Yaf_loader::import(APP_PATH . 'library/Weixin/weixinTemplate.class.php');
        $token = Tools_help::getToken();
        $template_obj = new weixinTemplate($token);
        if ($type == 1) {
            $data_send = array(
                'touser' => $openid,
                'template_id' => 'q61I9d85kuo3Kjrh-Fly2Y1sYLMSFPX-s22PmdJKAH4',
                'url' => 'http://www.dafabanjia888.com/mobileregister/orderinfo/order_number/'.$order_number,
                'topcolor' => '#00A600',
                'data' => array(
                    'first' => array(
                        'value' => '大发起重公司消息',
                        'color' => '#173177'
                    ),
                    'keyword1' => array(
                        'value' => '搬运服务',
                        'color' => '#000000'
                    ),
                    'keyword2' => array(
                        'value' => $data['order_number'],
                        'color' => '#173177'
                    ),
                    'keyword3' => array(
                        'value' => '1',
                        'color' => '#173177'
                    ),
                    'keyword4' => array(
                        'value' => $data['cash_fee'],
                        'color' => '#173177'
                    ),
                    'keyword5' => array(
                        'value' => $data['time_end'],
                        'color' => '#173177'
                    ),
                    'remark' => array(
                        'value' => '感谢使用我们的服务，我们致力于成为地球最快的搬家公司',
                        'color' => '#173177'
                    ),
                ),
            );
        } else {
            $data_send = array(
                'touser' => $openid,
                'template_id' => '6T4pAnetgJZCayvQ5an31eMPDO_I_v_zuZZul7YBqSY ',
                'url' => 'www.qq.com ',
                'topcolor' => '#00A600',
                'data' => array(
                    'first' => array(
                        'value' => '大发起重公司消息',
                        'color' => '#173177'
                    ),
                    'keyword1' => array(
                        'value' => '00665555',
                        'color' => '#000000'
                    ),
                    'keyword2' => array(
                        'value' => 'fuck wx',
                        'color' => '#000000'
                    ),
                    'remark' => array(
                        'value' => '感谢使用我们的服务，我们致力于成为地球最快的搬家公司',
                        'color' => '#173177'
                    ),
                ),
            );
        }
        $send_msg = $template_obj->sendMessageTemplate($data_send);
        $cache_config = $this->config['cache'];
        $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);      
        $cache->set('payinfo',$send_msg);
    }

    public function fetchDataAction() {
//        $cache_config = $this->config['cache'];
//        $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
//        $postStr = '<xml>
//            <return_code><![CDATA[SUCCESS]]></return_code>
//            <return_msg><![CDATA[OK]]></return_msg>
//            <appid><![CDATA[wx2421b1c4370ec43b]]></appid>
//            <mch_id><![CDATA[10000100]]></mch_id>
//            <nonce_str><![CDATA[IITRi8Iabbblz1Jc]]></nonce_str>
//            <sign><![CDATA[7921E432F65EB8ED0CE9755F0E86D72F]]></sign>
//            <result_code><![CDATA[SUCCESS]]></result_code>
//            <prepay_id><![CDATA[wx201411101639507cbf6ffd8b0779950874]]></prepay_id>
//            <trade_type><![CDATA[JSAPI]]></trade_type>
//         </xml>';
//        appid=>wxc7623e0af9e9ca6e
//bank_type=>CFT
//cash_fee=>1
//fee_type=>CNY
//is_subscribe=>Y
//mch_id=>1332724401
//nonce_str=>kcpqn7068dk7ek5p773d0cv1g99jbf2z
//openid=>o3QGWvyynxtKw2PAsy5bxlssICPA
//out_trade_no=>qy-Z-201605105150
//result_code=>SUCCESS
//return_code=>SUCCESS
//sign=>7BE7252D227ABD416B32D9F524FAFD80
//time_end=>20160510110641
//total_fee=>1
//trade_type=>JSAPI
//transaction_id=>4000292001201605105694690395
//        $cache->set('payinfo','hello');
       // $this->sendTemp(1,$data,$openid);exit;
        $postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : '';
        libxml_disable_entity_loader(true);
        
        
        //实例化xml对象
        $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);
        //print_r($postObj);
       // $cache->set('payinfo',$postStr);
        $order_number = $postObj->out_trade_no;
        $result_code = $postObj->result_code;
        $time_end = strtotime($postObj->time_end);
        $cash_fee = ($postObj->cash_fee/100);
        $openid = $postObj->openid;
        $orderModel = new OrderModel();
        $state = $orderModel->select(array('field'=>array('order_state'),'where'=>array('order_number'=>$order_number)));

        if (!empty($result_code) && $result_code == 'SUCCESS' && $state['order_state'] == '0') {
                        
            //改变状态
            $update = array();
            
            //核销卡券
            if(!empty($postObj->attach)){
                $card = (string)$postObj->attach;
                $card = json_decode($wechat);
                
                Yaf_Loader::import(APP_PATH . 'library/Weixin/wechatCard.php');
                $weixincard = new wechatCard();
                $weixincard->consumeCard($card['card_code']);       
                $update['card_fee'] = $card['card_fee'];
                $update['card_title'] = $card['card_title'];
            }
            
            $update['already_price_time'] = $time_end;
            $update['already_price'] = $cash_fee;
            $update['order_state'] = 1;
            $rs = $orderModel->update(array('order_number' => $order_number), $update);
            //print_r($rs);exit;
            //发送模版消息
            $data = array();
            $data['order_number'] = $order_number;
            $data['cash_fee'] = $cash_fee;
            $data['time_end'] = date("Y-m-d H:i:s",$time_end);
            $cache->set('payinfo','in');
           $this->sendTemp(1,$data,$openid);
        }

//        $str = "";
//        foreach($postObj as $k=>$v){
//            $str .= $k.'=>'.$v.'</br>';
//        }
//        $cache_config = $this->config['cache'];
//        $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
//        //var_dump($postObj);exit;
//        $return_code = $postObj->return_code;
//        
//        $cache->set('payinfo',$str);
        exit;
    }

    public function showDataAction() {
        $cache_config = $this->config['cache'];
        $cache = Cache_Cache::create($cache_config, Cache_Cache::TYPE_FILE);
        echo $cache->get('payinfo');
        exit;
    }
    
    public function makecomboordernewAction(){
        
    }

}
